//引入模块
const express = require("express");
const query = require("../util/query.js");
const JWT = require('../util/token.js');

//创建空路由器
let router = express.Router();
//==============================
// 收货地址管理模块
//===============================================
//1 保存/新增收货地址 POST /address/save
// 参数名	参数说明	备注
// id	可选参数，如果有id表示做编辑操作，如果没有id参数表示做新增操作
// name 姓名
// tel 电话
// province 省份
// city 城市
// county 区县
// area_code 地区编码，通过省市区选择获取（必填）
// postal_code 邮政编码
// address_detail 详细地址
// is_default 是否选择默认0 | 1
router.post("/save", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //获取数据
    let { id, name, tel, province, city, county, area_code, postal_code, address_detail, is_default } = req.body;
    id = parseInt(id);

    if (!name) throw new Error("收货人姓名不能为空");
    if (!tel) throw new Error("收货人手机号不能为空");
    if (!address_detail) throw new Error("详细地址不能为空");

    let user_id = user.id;
    //address对象必须要和表字段一致
    let address = { 
      user_id, 
      receiver:name, 
      cellphone:tel, 
      province, 
      city, 
      county, 
      areacode:area_code, 
      postcode:postal_code, 
      address:address_detail, 
      is_default 
    };


    if (id) {  //id不为0
      let sql = `select * from lz_receiver_address where id = ${id}`;
      let result = await query(sql);
      if (result.length == 0) throw new Error("记录不存在");

      sql = "UPDATE lz_receiver_address SET ? WHERE id=?";
      result = await query(sql, [address, id]);
      //如果数据更改成功，响应对象
      if (result.affectedRows > 0) res.send({ code: 1, msg: "更改成功", data: { id } });
      else throw new Error("保存失败");

    } else {
      let sql = "INSERT INTO lz_receiver_address SET ?";
      let result = await query(sql, [address]);
      res.send({ code: 1, msg: "保存成功", data: { id: result.insertId } });
    }
  } catch (error) {
    res.send({ code: -1, msg: error.message });
    return;
  }
});

//===============================================
//2 查询登录用户的收货地址列表 GET /address/list
router.get("/list", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //执行SQL语句 ,返回当前登录用户的地址列表
    let sql = `select * from v_receiver_address where user_id =${user.id} `;
    let result = await query(sql);
    let data = result;
    res.send({ code: 1, msg: "获取成功", data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});

//===============================================
//3查询收货地址详情 GET /address/detail
// 参数名	参数说明	备注
// id	收货地址id	
router.get("/detail", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //1获取数据 
    let id = parseInt(req.query.id);
    //验证数据
    if (!id) throw new Error("收货地址编号不能为空");
    //执行SQL语句
    let sql = `select * from v_receiver_address where user_id = ${user.id} AND id = ${id}`;
    let result = await query(sql);
    let data = result[0];  //只有对应的1条数据
    res.send({ code: 1, msg: "获取成功", data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});


//===============================================
//4 根据id删除收货地址 POST /address/delete
// 参数名	参数说明	备注
// id	收货地址id
router.post("/delete", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //1获取数据 
    let id = parseInt(req.body.id);
    //验证数据
    if (!id) throw new Error("收货地址id不能为空");

    //执行SQL语句
    let sql = `delete from lz_receiver_address where user_id = ${user.id} AND id = ${id}`;
    await query(sql);
    res.send({ code: 1, msg: "删除成功" });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});

//===============================================
//5 获取默认的收货地址
// 参数名	 参数说明	
// id	    可选参数，如果传递了id就获取id对应的收货地址，
//        如果没有传递id就获取默认的收货地址	
router.get("/default", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //1获取数据
    let id = req.query.id;
    id = parseInt(id);
    //2验证数据
    //3 执行SQL语句
    let sql;
    if (!id) {  
      sql = `select * from v_receiver_address where user_id = ${user.id} ORDER BY is_default DESC,id DESC LIMIT 1`;
    } else {
      sql = `select * from v_receiver_address where user_id = ${user.id} AND id = ${id}`;
    }
    console.log(sql);

    let result = await query(sql);
    let data = result;
    res.send({ code: 1, msg: "获取成功", data });

  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});

//===============================================
//导出路由器
module.exports = router;